<?php
require_once "xpface/util/PostData.class.php";
require_once "xpface/util/XPFaceConfigLoader.class.php";
require_once "pworks/mvc/IFilter.iface.php";
require_once "pworks/common/httputil/DefaultHttpInputValidation.class.php";
require_once('pworks/util/MemcacheHelper.class.php');

class CheckPermissionFilter implements IFilter {
	public function before(IAction &$action) {
        $page_id = DefaultHttpInputValidation::getDate(HttpConst::TYPE_REQUEST, "page_id");
        //xpface config
        $xpFaceConfigLoader = XPFaceConfigLoader::getInstance();
        $xpFaceConfig = $xpFaceConfigLoader->getXPFaceConfig();
        //var_dump($xpFaceConfig);
        
        //page config
        $pageConfig = $xpFaceConfigLoader->getPageConfig();
        //var_dump($pageConfig);
        $_config = $pageConfig[$page_id];
        //var_dump($_config);
        if ($_config->permission == "yes") {
            $sessid = $_COOKIE["__sessid__"];
            $result = null;
            if (strlen($sessid) > 0) {
                //$cacheKey = "USER_PERMISSION_LIST_DATA".$sessid;
                //var_dump($cacheKey);
                //$result = MemcacheHelper::get($cacheKey);
            }
            if (!$result) {
                $userPermissionListApi = str_replace("#API_NAME#", "LoadUserPermissionList", WS_SERVICE);
                $result = PostData::post($userPermissionListApi, array());
                //var_dump($result);
                //MemcacheHelper::set($cacheKey, $result);
            }
            //var_dump($result);
            $resultData = json_decode($result, true);
            //var_dump($resultData->data, $page_id);
            $pagePermissions = $resultData["body"]["data"][$page_id];
            //var_dump($pagePermissions);
            if (count($pagePermissions) <= 0) {
                if (get_class($action) == "XPFaceAction") {
                    header("Location: permission.html");
                    exit;
                }
                echo "<script>location = \"permission.html\";</script>";
                //$action->exception("NO_PERMISSION");
                exit;
            }
            //var_dump($pagePermissions);
            $action->setData("__permission__", $pagePermissions);
        }
        return null;
	}

	public function after(IAction &$action) {

		if (TRUE == $action->ut)
		{
			return 'succ';
		}
		return null;
	}
}
